import { DrawerForm, ProFormText } from '@ant-design/pro-components';
import { Button, Form } from 'antd';
import { useState } from 'react';
import api from './request';

export type FormConfig = { Component: any; props: Record<string, any> };
export interface Props {
  data: OrderListManagementApi.ListResponse;
  onSuccess?: () => void;
  onCancel?: () => void;
}
function DeliveryForm(props: Props) {
  const [form] = Form.useForm();
  const [formData, setFormData] = useState<any>({});
  const [info, setInfo] = useState<Partial<OrderListManagementApi.InfoResponse>>({});

  const getInfo = async (params: OrderListManagementApi.InfoParams) => {
    const info = await api.getInfo(params);
    setInfo(info);
    form.setFieldsValue(info);
    setFormData(info);
  };

  const onOpenChange = (open: boolean) => {
    if (open) {
      if (props.data && props.data.orderID) {
        getInfo({ OrderId: props.data.orderID });
      }
    } else {
      form.resetFields();
      setFormData({});
      props.onCancel?.();
    }
  };

  const onSubmit = async () => {
    const { orderID = '' } = info;
    const { deliveryOrderNumber, expressName } = formData;
    const params: OrderListManagementApi.DeliveryParams = {
      deliveryOrderNumber,
      expressName,
      orderId: orderID,
    };
    const data = await api.updateDelivery(params);
    if (data.success) props.onSuccess?.();
    return data.success;
  };

  return (
    <DrawerForm
      autoFocusFirstInput
      title={`更新快递`}
      form={form}
      drawerProps={{ destroyOnClose: true }}
      resize={{
        maxWidth: window.innerWidth * 0.8,
        minWidth: 400,
        onResize() {},
      }}
      trigger={<Button type="link">更新快递</Button>}
      onOpenChange={onOpenChange}
      onFinish={onSubmit}
    >
      <ProFormText
        width="md"
        name="deliveryOrderNumber"
        label="快递单号"
        placeholder="请输入快递单号"
        rules={[{ required: true }]}
        fieldProps={{
          value: formData.deliveryOrderNumber,
          onChange: (e) => setFormData({ ...formData, deliveryOrderNumber: e.target.value }),
        }}
      />
      <ProFormText
        width="md"
        name="expressName"
        label="快递名称"
        placeholder="请输入快递名称"
        rules={[{ required: true }]}
        fieldProps={{
          value: formData.expressName,
          onChange: (e) => setFormData({ ...formData, expressName: e.target.value }),
        }}
      />
    </DrawerForm>
  );
}

export default DeliveryForm;
